package info.xiao.dataStructrue.stack;

import java.util.Arrays;

/**
 * @Classname MyStack 栈
 * @Description 模拟栈结构
 * @Date 2022/10/20 10:47
 * @Created by 晓龙Oba
 */
public class MyStack<T> {
    // 通过数组充当内存容器
    private Object[] pot;
    // 栈顶指针
    private Integer topIndex = 0;
    // 最大元素数量
    private Integer max_counts = 5;

    public MyStack() {
        pot = new Object[max_counts];
    }


    public void push(T element) {
        // 判断此时的栈是否已经满了
        if (topIndex >= max_counts) {
            // 扩容
            max_counts = max_counts * 2;
            pot = Arrays.copyOf(pot, max_counts);
        }
        pot[topIndex++] = element;
    }

    public T pop() {
        //栈顶指针后移
        topIndex--;
        // 校验是否超出栈空间范围
        if (topIndex < 0) {
            throw new IndexOutOfBoundsException("超出栈空间");
        }
        // 完成弹栈操作
        T temp = (T) pot[topIndex];
        pot[topIndex] = null;
        return temp;
    }

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder("当前栈内元素有:");
        Arrays.stream(pot).forEach(item -> {
            if (item != null) {
                result.append("\r\n" + item);
            }
        });
        return result.toString();
    }
}
